<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="讲师类型" prop="teacherType">
        <el-select v-model="formData.teacherType" placeholder="请选择讲师类型">
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.EHS_TEACHER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="培训范围" prop="trainScopeId">
        <el-tree
          ref="treeRef"
          @check-change="scopeCheckChange"
          :data="deptList"
          :props="defaultProps"
          :check-strictly="!checkStrictly"
          node-key="id"
          placeholder="请选择培训范围"
          show-checkbox
        />
      </el-form-item>
      <el-form-item label="培训人" prop="teacherId">
        <el-select v-model="formData.teacherId" placeholder="请选择培训人" @change="changeTeacher"  clearable style="width: 100%">
          <el-option v-for="item in users" :key="parseInt(item.id)" :label="item.nickname" :value="parseInt(item.id)" />
        </el-select>
      </el-form-item>
      <el-form-item label="培训内容" prop="content">
<!--        <Editor v-model="formData.content" height="150px" />-->
        <el-input v-model="formData.content" type="textarea" :rows="8" placeholder="请输入培训内容" />
      </el-form-item>
      <el-form-item label="培训人数" prop="trainNum">
        <el-input v-model="formData.trainNum" type="number" placeholder="请输入培训人数" />
      </el-form-item>
      <el-form-item label="培训照片" prop="trainPics">
        <UploadImgs v-model="formData.trainPics"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TrainRecordApi, TrainRecordVO } from '@/api/ehs/trainrecord'
import {DICT_TYPE, getDictOptions} from "@/utils/dict";
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from "@/api/system/dept";

/** EHS培训记录 表单 */
defineOptions({ name: 'TrainRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  teacherType: undefined,
  teacherId: undefined,
  teacherName: undefined,
  content: undefined,
  trainNum: undefined,
  trainPics: undefined,
  trainScopeId: undefined,
  trainScopeName: undefined,
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

const users = ref([])
const deptList = ref<Tree[]>([]) // 树形结构
const treeRef = ref() // 菜单树组件 Ref
const checkStrictly = ref(false) // 是否严格模式，即父子不关联

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TrainRecordApi.getTrainRecord(id)
      treeRef.value.setCheckedKeys(formData.value.trainScopeId)
    } finally {
      formLoading.value = false
    }
  }
  await getUserList();
  await getTrainScopeList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

//讲师
const getUserList = async () => {
  const result = await TrainRecordApi.listSimpleUsers({})
  users.value= result;
}

const getTrainScopeList = async () => {
  /** 查询部门下拉树结构 + 岗位下拉 */
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}

const changeTeacher = (val: number) => {
  formData.value.teacherName = users.value.find((item) => item.id === val)?.nickname
}
const scopeCheckChange = () => {
  const checkedNodes = treeRef.value.getCheckedNodes();
  formData.value.trainScopeName = checkedNodes.map((item) => item.name)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TrainRecordVO
    data.trainScopeId = treeRef.value.getCheckedKeys(false)
    if (formType.value === 'create') {
      await TrainRecordApi.createTrainRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await TrainRecordApi.updateTrainRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    teacherType: undefined,
    teacherId: undefined,
    teacherName: undefined,
    content: undefined,
    trainNum: undefined,
    trainPics: undefined,
    trainScopeId: undefined,
    trainScopeName: undefined,
  }
  treeRef.value?.setCheckedNodes([])
  formRef.value?.resetFields()
}
</script>
